#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <windows.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->lcdNumber->display(0);
    ui->lcdNumber->display(0);

    // GUI 更新应该只在主线程（GUI线程）中执行
    //这个是重点
    connect(this, &MainWindow::updateOdd, this, &MainWindow::odd);
    connect(this, &MainWindow::updateEven, this, &MainWindow::even);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::printOdd()
{
    //使用 QMutexLocker 自动锁定和解锁
    QMutexLocker locker(&mutex);
    while (count < 100) {
        if (count % 2 == 0) {
            //奇数线程等待
            oddCondition.wait(&mutex);
        }
        emit updateOdd(count++);
        Sleep(1000);
        //醒打印偶数的线程
        evenCondition.wakeOne();
    }
}

void MainWindow::printEven()
{

    QMutexLocker locker(&mutex);
    while (count < 100) {
        if (count % 2 != 0) {
            // 偶数线程等待
            evenCondition.wait(&mutex);
        }
        emit updateEven(count++);
        Sleep(1000);
        //  唤醒打印奇数的线程
        oddCondition.wakeOne();
    }
}

void MainWindow::odd(int value)
{
    ui->lcdNumber->display(value);
}

void MainWindow::even(int value)
{
    ui->lcdNumber_2->display(value);
}

